package com.asset.dispoal.company.service.commom;

import com.asset.dispoal.company.domain.db.entity.SysCompanyDo;
import com.asset.dispoal.company.domain.db.mapper.SysCompanyMapper;
import com.asset.dispoal.company.dto.CompanyRequest;
import com.asset.dispoal.company.service.converter.CompanyConverter;
import com.asset.dispoal.department.domain.db.entity.SysDepartmentDo;
import com.asset.dispoal.department.domain.db.mapper.SysDepartmentMapper;
import com.asset.dispoal.menu.domain.db.mapper.GbMenuMapper;
import com.asset.dispoal.role.domain.db.entity.GbRoleDo;
import com.asset.dispoal.role.domain.db.mapper.GbRoleMapper;
import com.asset.dispoal.roleMenu.domain.db.mapper.GbRoleMenuMapper;
import com.asset.dispoal.user.dto.UserRequest;
import com.asset.dispoal.user.service.commom.UserRegisterCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author qr
 * @date 2022/1/25$
 */
@Component
public class InsertCommand implements BaseCommand<CompanyRequest, Result> {

    @Autowired
    SysCompanyMapper companyMapper;

    @Autowired
    BaseIdeable<String> snowFlake;

    @Autowired
    UserRegisterCommand userRegisterCommand;

    @Autowired
    GbMenuMapper gbMenuMapper;

    @Autowired
    GbRoleMapper gbRoleMapper;

    @Autowired
    GbRoleMenuMapper gbRoleMenuMapper;

    @Autowired
    SysDepartmentMapper sysDepartmentMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(CompanyRequest request) {
        if (request == null) {
            throw new BusinessException("参数错误");
        }
        //判断公式编号是否重复
        int count = companyMapper.queryCompanyCodeExist(request.getCode(), request.getType());
        if (count > 0) {
            throw new BusinessException(400, "公司编码重复！", request.getCode());
        }

        final SysCompanyDo sysCompanyDo = CompanyConverter.INSTANCE.reqToDo(request);
        final String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        String companyId = snowFlake.generateId();
        sysCompanyDo.setId(companyId);
        sysCompanyDo.setCreateTime(DateTimeUtil.currentDate());
        sysCompanyDo.setCreateUser(userId);
        companyMapper.insert(sysCompanyDo);
        List<String> list = gbMenuMapper.queryMenuByCompany(sysCompanyDo.getType(), null);
        if (CollectionUtil.isNotEmpty(list)) {
            gbMenuMapper.saveCompanyMenu(list, companyId);
        }

        //根据默认角色添加到角色列表
        GbRoleDo gbRoleDo = gbMenuMapper.queryDefaultRole(sysCompanyDo.getType());
        if (gbRoleDo != null) {
            gbRoleDo.setId(snowFlake.generateId());
            gbRoleDo.setCompanyId(companyId);
            gbRoleMapper.insert(gbRoleDo);
            //根据默认角色菜单关联添加到角色菜单关联
            List<String> collect = gbMenuMapper.queryDefaultMenuByRole(gbRoleDo.getId());
            if (CollectionUtil.isNotEmpty(collect)) {
                gbRoleMenuMapper.saveBatch(gbRoleDo.getId(), collect);
            }
        } else {
            throw new BusinessException(Result.SYS_FAILD, "请配置默认角色");
        }

        //根据默认部门添加到部门
        SysDepartmentDo sysDepartmentDo = sysDepartmentMapper.queryDefaultDepByCompanyType(sysCompanyDo.getType());
        if (sysDepartmentDo != null) {
            sysDepartmentDo.setId(snowFlake.generateId());
            sysDepartmentDo.setCompanyId(companyId);
            sysDepartmentMapper.insert(sysDepartmentDo);
        } else {
            throw new BusinessException(Result.SYS_FAILD, "请配置默认部门");
        }

        UserRequest userRequest = companyMapper.queryRoleDepByCompanyType(request.getType());
        if (userRequest != null) {
            userRequest.setRoleIds(Stream.of(gbRoleDo.getId()).collect(Collectors.toList()));
            userRequest.setDepIds(Stream.of(sysDepartmentDo.getId()).collect(Collectors.toList()));
            userRequest.setPassword(request.getPassword());
            userRequest.setAccount(request.getAccount());
            userRequest.setType(request.getType());
            userRequest.setCompanyId(companyId);
            Result<String> execute = userRegisterCommand.execute(userRequest);
            if (execute.getCode() != 200) {
                throw new BusinessException("服务器异常");
            }
        } else {
            throw new BusinessException(Result.SYS_FAILD, "请设置创建人的默认角色和部门");
        }
        return Result.ok();
    }
}
